<?php

namespace App\Controller;
use Think\Controller;
use Think\Hook;
use Api\Event\CacheEvent;

/** 
 * [app内置网页]
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */
class AppController extends Controller 
{
	public $user = null;

	var $testUids = [55, 54, 53, 3425, 86, 49, 76, 3473, 97, 3530];

	protected function _initialize()
	{

		$param = [
			'action'  => strtolower('App/'.CONTROLLER_NAME .'/'.ACTION_NAME), 
		];
		Hook::listen('api_init', $param);

        define('IS_MOBILE', is_mobile_request());

        $Redis = CacheEvent::instance(0);
        load_config($Redis);
        unset($Redis);
        C('TEST_UIDS') && $this->testUids = explode(',', C('TEST_UIDS'));
        $uid = $this->isLogin();
		$uid && $appToken = session('app_auth.appToken');

		if (I('appToken'))
		{
			$appToken = I('appToken', '', 'trim');
			$uid = $this->getUid($appToken);
			if (!$uid)
			{
				return $this->loginErr();
			}
			$user = event('User')->info($uid);
			$data = [
				'uid' 		=> $user['id'],
				'nickname' 	=> $user['nickname'],
				'appToken'  => $appToken,
			];
			session('app_auth', $data);
			session('app_auth_sign', data_auth_sign($data));
		}
		
		define('UID', (int)$uid);
		if ($uid && !$user)
		{
			$user = event('User')->info($uid);
		}
		$user && $user['appToken'] = $appToken;
		$this->user = $user;
	}

	protected function isLogin()
	{
		$user = session('app_auth');
		return session('app_auth_sign') === data_auth_sign($user) ? $user['uid'] : 0;
	}

	protected function showError($error = 'error')
	{
		exit($error);
		// return $this->show('public.error');
	}

	protected function jsonList($object)
	{
		$ret = [];
		$ret['count'] = count($object);
		$ret['lists'] = $object;
		$this->ajaxReturn($ret);
	}

	protected function getUid($appToken = ''){   // 修改可为空情况
		static $uid = null;
		if ($uid === null)
		{
			$map = array(
				// 'status'=>1,
				'app_token'=>trim($appToken),
			);
			$uid = service('Token')->where($map)->find()['uid'] ?: 0;
 
		}
		return $uid ?: 0;
	}

	protected function loginErr()
	{
		exit('not login!');
		return $this->show('public.unlogin');
	}
 
	protected function json_login_error()
	{
		$this->error('unlogin', '', true);
	}

	// 数据格式化 只保留需要的数据
    protected function field_filter( $data, $filter_map ) {
        if ( !$data ) {
            return;
        }
        foreach ( $data as $key => $value ) {
            if ( !in_array( $key, $filter_map ) ) {
                unset( $data[$key] );
            }
            else if ( !isset( $value ) ) {
                    $data[$key] = '';
                }
        }
        return $data;
    }
}